package 线程池;

import java.util.concurrent.*;

public class Callable任务线程池 {
    public static void main(String[] args) {

        ExecutorService pools = Executors.newFixedThreadPool(3);

//        提交任务，任务参数不同，所以要创建多个线程任务对象
//        返回值是未来任务类型，Future是FutureTask的父类
        Future<String> future0 = pools.submit(new MyCallable(100));
        Future<String> future1 = pools.submit(new MyCallable(200));
        Future<String> future2 = pools.submit(new MyCallable(300));
        Future<String> future3 = pools.submit(new MyCallable(400));

        try {
//            获取线程执行的结果
            String result0 = future0.get();
            String result1 = future1.get();
            String result2 = future2.get();
            String result3 = future3.get();

            System.out.println(result0);
            System.out.println(result1);
            System.out.println(result2);
            System.out.println(result3);

        } catch (Exception e) {
//            打印异常栈信息
            e.printStackTrace();
        }

        pools.shutdown();
    }
}

class MyCallable implements Callable<String> {

    private int n ;

    public MyCallable(int n) {
        this.n = n;
    }

    @Override
    public String call() throws Exception {
        int sum = 0 ;
        for (int i = 0 ; i < n ; i++) {
            sum += i ;
        }
        return Thread.currentThread().getName()+"执行的结果是:"+sum;
    }
}